# _*_ coding:utf-8 _*_
# @File  : article.py
# @Time  : 2022-01-07  17:56
# @Author: zizle


from fastapi import APIRouter, Body
from pydantic import BaseModel
from status import r_status
from utils.datetime_util import verify_datetime_format
from db import FAConnection

qhrb_article_admin = APIRouter()


class QhrbArticleItem(BaseModel):
    create_time: str
    raw_time: str
    title: str
    authors: str
    words: str
    issue_num: str
    layout: int
    is_special: int
    content: str


@qhrb_article_admin.post('/', summary='上传一篇期货日报文章')
async def create_article(article: QhrbArticleItem = Body(...)):
    create_time = verify_datetime_format(article.create_time, f='%Y-%m-%d %H:%M:%S')
    raw_time = verify_datetime_format(article.raw_time, f='%Y-%m-%d %H:%M:%S')
    if not all([create_time, raw_time]):
        return {'code': r_status.VALIDATE_ERROR, 'message': '数据时间格式错误'}

    create_sql = 'INSERT INTO qhrb_article (create_time,raw_time,title,authors,words,issue_num,layout,is_special,content) ' \
                 'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);'
    params = [create_time, raw_time, article.title, article.authors, article.words, article.issue_num, article.layout,
              article.is_special, article.content]
    db_conn = FAConnection(conn_name='添加期货日报文章')
    _, success = db_conn.execute(create_sql, params)
    if success:
        return {'code': r_status.CREATED_SUCCESS, 'message': '创建期货日报文章成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '创建文章失败，服务器错误!'}

